<template>
  <a-modal
    :visible="visible"
    :title="!$isEmpty(propsData) ? '修改短信模板' : '添加短信模板'"
    :width="900"
    :confirm-loading="isSubmiting"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <a-spin :spinning="spinning">
      <a-form :form="form">
        <a-form-item label="短信类别">
          <a-input
            v-decorator="['DX_LB', { rules: [{ required: true, message: '请输入短信类别' }] }]"
            placeholder="请输入短信类别"
          />
        </a-form-item>
        <a-form-item label="短信内容">
          <a-textarea
            v-decorator="['DX_NR', { rules: [{ required: true, message: '请输入短信内容' }] }]"
            placeholder="请输入短信内容"
          />
        </a-form-item>
      </a-form>
      <div>
        <a-divider orientation="left">短信接收人员</a-divider>
        <div class="text-right">
          <a-tooltip title="选择系统中存在的用户">
            <y-button type="primary" size="small" icon="plus" @click="visibleChoose = true">选择人员</y-button>
          </a-tooltip>
          <a-tooltip title="添加任意姓名、电话">
            <y-button type="primary" size="small" icon="plus" @click="handleUserForm(true)">添加人员</y-button>
          </a-tooltip>
        </div>
        <a-list item-layout="horizontal" :data-source="userList">
          <a-list-item slot="renderItem" slot-scope="item, index">
            <y-button type="link" slot="actions" @click="handleUserForm(false, item, index)">修改</y-button>
            <y-button type="link" slot="actions" @click="handlerRemoveUser(item, index)">删除</y-button>
            <a-list-item-meta :description="item.phone" :title="item.LevelUserStation">
              <a-avatar slot="avatar">{{ item.avatar }}</a-avatar>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
      </div>
      <div>
        <a-divider orientation="left">附件上传</a-divider>
        <file-list ref="file" tableNames="Other_DXFS" :fileList="detail.XGWJJH"></file-list>
      </div>
    </a-spin>
    <choose-user
      :defaultValue="defaultUserList"
      :visible.sync="visibleChoose"
      @success="handleChooseSuccess"
    ></choose-user>
    <user-form
      :defaultValue="userList"
      :propsData="propsUserData"
      :visible.sync="visibleUserForm"
      @success="handleUserFormSuccess"
    ></user-form>
  </a-modal>
</template>

<script>
/**
 *Parser
 *@Author
 *@Version
 *@property
 *@event
 */
import FileList from '@/components/FileList/FileList'
import ChooseUser from './choose.vue'
import UserForm from './userForm.vue'
import { sendSms, getSmsDetail } from '@/api/sms'
import moment from 'moment'
export default {
  components: {
    FileList,
    ChooseUser,
    UserForm
  },
  props: {
    propsData: {
      type: Object,
      default: () => {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    visible (n) {
      if (n) {
        this.fetchData()
      }
    }
  },
  data () {
    return {
      isSubmiting: false,
      spinning: false,
      detail: {},
      form: this.$form.createForm(this, { name: 'smsForm' }),
      userOptions: [],
      defaultUserList: [],
      userList: [],
      visibleChoose: false,
      visibleUserForm: false,
      propsUserData: {},
      userIndex: ''
    }
  },
  methods: {
    fetchData () {
      if (!this.$isEmpty(this.propsData)) {
        this.spinning = true
        getSmsDetail({
          DXID: this.propsData.ID
        })
          .then((res) => {
            this.detail = res.data
            this.$nextTick(() => {
              const { DX_LB, DX_NR, DX_JSR, DX_JSRDH } = this.detail
              this.form.setFieldsValue({
                DX_LB,
                DX_NR
              })
              const nameArr = DX_JSR.split(',')
              const phoneArr = DX_JSRDH.split(',')
              nameArr.forEach((name, index) => {
                const phone = phoneArr[index]
                this.userList.push({
                  avatar: name.substr(0, 1),
                  LevelDeptID: '',
                  LevelDeptName: '',
                  LevelUserStation: name,
                  LevelUserID: '',
                  phone
                })
              })
              this.defaultUserList = this.userList
            })
          })
          .finally(() => {
            this.spinning = false
          })
      }
    },
    handleChooseSuccess (e) {
      this.userList = e.map((e) => {
        e.avatar = this.$isEmpty(e.LevelUserStation) ? '' : e.LevelUserStation.substr(0, 1)
        return e
      })
    },
    handlerRemoveUser (e, i) {
      this.userList.splice(i, 1)
      this.defaultUserList = this.userList
    },
    handleUserForm (isAdd, row = {}, index = '') {
      this.propsUserData = row
      this.userIndex = index
      this.visibleUserForm = true
    },
    handleUserFormSuccess (e) {
      const { data, type } = e
      data.avatar = this.$isEmpty(data.LevelUserStation) ? '' : data.LevelUserStation.substr(0, 1)
      if (type === 'edit') {
        // 只处理电话与姓名
        const { LevelUserStation, phone } = data
        this.$set(this.userList[this.userIndex], 'phone', phone)
        this.$set(this.userList[this.userIndex], 'LevelUserStation', LevelUserStation)
      } else {
        this.userList.push(data)
      }
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.$isEmpty(this.userList)) {
            this.$message.error('请添加短信接收人员！')
            return
          }
          this.isSubmiting = true
          const propsDataEmpty = this.$isEmpty(this.propsData)
          sendSms({
            State: propsDataEmpty ? 'add' : 'update',
            other_dxfs_Modules: Object.assign(
              {
                ID: this.propsData.ID || '',
                DX_FSR: this.$store.getters.nickname,
                DX_FSRID: this.$store.getters.userid,
                DX_JSR: this.userList.map((e) => e.LevelUserStation).join(','),
                DX_JSRDH: this.userList.map((e) => e.phone).join(','),
                DX_FSSJ: '',
                DX_FSJG: '',
                CreateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                CreateUserID: this.$store.getters.userid,
                CreateUserName: this.$store.getters.nickname,
                Mode: this.propsData.Mode || '0',
                XGWJJH: this.$refs.file.fileData
              },
              values
            )
          })
            .then((res) => {
              this.$message.success('短信模板创建完成！')
              this.$emit('success', propsDataEmpty)
              this.handleClose()
            })
            .finally((this.isSubmiting = false))
        }
      })
    },
    handleClose () {
      Object.assign(this.$data, this.$options.data.call(this))
      this.form.resetFields()
      this.$emit('update:visible', false)
    }
  }
}
</script>
<style scoped></style>
